﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

/// <summary>
///DBHelper 的摘要说明
/// </summary>
/// 
namespace DB
{
    public class DBHelper
    {
        static SqlConnection conn;
        public DBHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        public static SqlConnection  Connection
        {

            get
            {
               // string ConnectionString = "server=.;database=学生档案管理系统;uid=sa;pwd=2013gfy; MultipleActiveResultSets=true";
                string ConnectionString = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
                if (conn == null)
                {
                    conn = new SqlConnection(ConnectionString);
                    conn.Open();
                }
                else if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                else if (conn.State == ConnectionState.Broken)
                {
                    conn.Close();
                    conn.Open();
                }
                return conn;
            }
            
        }

        // 关闭数据库连接
        public static void Close()
        {
            conn.Close();
        }

        public static SqlDataReader Exc(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql,Connection);
            SqlDataReader dr = cmd.ExecuteReader();
            return dr;
        }

        public static DataSet Exc2(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Connection);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sql, Connection);
            da.Fill(ds);
            return ds;
        }

        public static SqlCommand Exc3(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Connection);
            return cmd;
        }


        //执行并返回影响行数
        public static int ExecuteCommand(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Connection);
            int count = cmd.ExecuteNonQuery();
            return count;
        }

        //执行并返回执行结果中的第一列
        public static int GetScalar(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql,Connection);
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            return count;
        }

        public static string  GetScalar1(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, Connection);
            string result = Convert.ToString(cmd.ExecuteScalar());
            return result;
        }
    }
}